import subprocess
from urllib import parse
from ZiMoooModule.system import is_port_in_use,get_new_port
STATUS_NO_INSTALL = 0
STATUS_STOP = -1
STATUS_RUNING = 1
STATUS_NO_STATUS = -2

def excmd(cmd):
    try:
        result = subprocess.check_output(cmd, text=True)
        # print(result.strip())
        res = parse.quote(result.strip()).replace("%00", "").replace("%0A", "").replace(
            "%E8%9A%AB%5CO%10b%E7%83%BA%E5%AD%BE%10b%020",
            "%E6%93%8D%E4%BD%9C%E6%88%90%E5%8A%9F%E5%AE%8C%E6%88%90%E3%80%82")
        return parse.unquote(res)
    except subprocess.CalledProcessError as e:
        res = parse.quote(e.output.strip()).replace("%00", "")
        return parse.unquote(res)


def server_status(servername="Redis50141"):
    resp = excmd("sc query %s" % (servername))
    print(resp)
    if "STOPPED" in resp:
        return STATUS_STOP
    elif "未安装" in resp:
        return STATUS_NO_INSTALL
    elif "RUNNING" in resp:
        return STATUS_RUNING
    else:
        return STATUS_NO_STATUS

def install_server(path=".\\Redis", port=50141, servername="Redis50141"):
    cmd = f"{path}\\redis-server --service-install {path}\\redis.windows.conf --service-name {servername} --port {port}"
    resp = excmd(cmd)
    print(resp)
    if "successfully" in resp:
        return True
    else:
        return False

def uninstall_server(path=".\\Redis", servername="Redis50141"):
    cmd = f"{path}\\redis-server --service-uninstall --service-name {servername}"
    resp = excmd(cmd)
    print(resp)
    if "successfully" in resp:
        # excmd(f"sc delete {servername}")
        return True
    else:
        return False

def start_server(path=".\\Redis", servername="Redis50141"):
    cmd = f"{path}\\redis-server --service-start --service-name {servername}"
    resp = excmd(cmd)
    print(resp)
    if "successfully" in resp:
        return True
    else:
        return False

def stop_server(path=".\\Redis", servername="Redis50141"):
    cmd = f"{path}\\redis-server --service-stop --service-name {servername}"
    resp = excmd(cmd)
    print(resp)
    if "successfully" in resp:
        return True
    else:
        return False


# # 创建连接池
# pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
#
# # 从连接池中获取一个连接
# r = redis.Redis(connection_pool=pool)
#
# # 使用Redis连接执行操作
# r.set('key', 'value')
# print(r.get('key'))  # 输出 b'value'
#
# # 关闭连接池（通常在应用程序关闭时进行）
# pool.disconnect()

def auto_install_redis(path=".\\redis",servername="redis50141",port=50141):
    status = server_status(servername=servername)
    if status == STATUS_RUNING:
        return port
    elif status == STATUS_STOP:
        if start_server(servername=servername, path=path):
            return port
        else:
            return 0
    else:
        uninstall_server(path=path,servername=servername)
        if is_port_in_use(port):
            port = get_new_port()
        install_server(path=path, servername=servername, port=port)
        if start_server(servername=servername,path=path):
            return port
        else:
            return 0


if __name__ == '__main__':
    uninstall_server()
    if auto_install_redis(path="E:\\redis"):
        print("redis 启动成功")
    else:
        print("redis 启动失败")
    pass
